<?php
declare(strict_types=1);

namespace App\Model\Data\Specific;


use App\Common\Component\RedisComponent;
use App\Model\Dao\Specific\IServerUser;
use App\Model\Data\AbstractData;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Db\Eloquent\Model;
use Swoft\Db\Query\Builder;
use Model\Entity\UserEntity;
use Tool\Token;
use Swoft\Db\Eloquent\Collection;
use App\Model\Entity\ChatUser;
use Swoft\Redis\Pool;

/**
 * Class ServerUserData
 * @Bean()
 * @package App\Model\Data\Specific
 */
class ServerUserData extends AbstractData implements IServerUser
{
    use RedisComponent;
    
    private string $tableName;
    
    public function __construct()
    {
        $this->tableName = 'chat_user';
        
//         $this->queryBuild = $this->getModel();
    }
    
    /**
     * {@inheritdoc}
     */
    protected function getParseResultByAdd(): array
    {
        $time =  time();
        return [
            'create_time' => $time,
            
            'update_time' => $time
        ];
    }
    
    
    /**
     * 根据用户名获取数据
     * @param string $userName
     * @return array
     */
    public function getUserInfoByUserName(array $userData): ?ChatUser
    {
        return $this->getModel()->where('user_name', '=', $userData['user_name'])->first([
           'id', 'user_name', 'password'
        ]);
    }

    /**
     * 处理登录或注册用户
     * {@inheritDoc}
     * @see \App\Model\Dao\Specific\IServerUser::parseUser()
     */
    public function parseUser(array $userData, string &$errorMessage): string
    {
        $userInfo = $this->getUserInfoByUserName($userData);
        
        $salt = config('app.salt');
        
        $password= md5($userData['password'].$salt);
        
        $token = md5(sha1($password.$salt.$userData['user_name']));
        
        if ($userInfo) {
            if ($password == $userInfo->getPassword()) {
               
               $this->redis->set($token, $userInfo->getId(), 86400 * 7);
                
               return $token;
            }
            
            $errorMessage = '用户名或密码不正确';
            
            return '';
        }
        
        $id = $this->add([
            'user_name' => $userData['user_name'],
            'password' => $password
        ]);
        
        if (0 === $id) {
            $errorMessage = '添加用户失败';
            return '';
        }
        
        $this->redis->set($token, $id, 86400 * 7);
        
        return $token;
    }
    
    
    public function getModel(): Model
    {
        return ChatUser::new();
    }

    /**
     * @param array $userData
     * @return bool
     *
     */
    public function checkUser(array $userData): string
    {
        $data = $this->getUserInfoByUserName($userData);
        if (!$data) {
            return '';
        }

        $salt = config('app.salt');

        if (md5($userData['password'].$salt) !== $data['user_pwd']) {
            return '';
        }

        $signCode = md5($salt.$data['id']);

        $this->redis->hSet('user_id', $signCode, $data['id']);

        return $signCode;
    }
    
    /**
     * 
     * {@inheritDoc}
     * @see \App\Model\Dao\Specific\IServerUser::searchUserByUserName()
     */
    public function searchUserByUserName(array $userData): Collection
    {
        return $this->getModel()->where('user_name', 'like', $userData['user_name'].'%')->limit(100)->get([
            'id', 'user_name'
        ]);
    }
    
    /**
     * 获取用户好友
     * @param Collection $friendCollection
     * @return Collection
     */
    public function getUserDataByFriendId(Collection $friendCollection):Collection
    {
        return $this->getModel()->whereIn('id', $friendCollection)->get(['id','user_name']);
    }
    
    
    public function getRedis(): Pool
    {
        return $this->redis;
    }
    
}